package cn.jdemo.juc.highquality.rpc_brief.client;

import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.net.Socket;
import java.net.UnknownHostException;

public class RpcClientProxy {
	
	public <T> T rpcServer(Class<T> class1) throws UnknownHostException, IOException {
		
		// 获取当前线程的classloader
		/*ClassLoader classLoader = IHello.class.getClassLoader();
		Class<?>[] classes = IHello.class.getClasses();*/
		
		Object newProxyInstance = Proxy.newProxyInstance(class1.getClassLoader(), class1.getInterfaces(), new InvocationHandler() {
		// Object newProxyInstance = Proxy.newProxyInstance(classLoader, classes, new InvocationHandler() {
			
			public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
				
				// 调用远程服务
				Socket socket = new Socket("localhost", 9999);
				OutputStream outputStream = socket.getOutputStream();
				ObjectOutputStream oStream = new ObjectOutputStream(outputStream);
				
				oStream.writeUTF(method.getName());
				oStream.writeObject(args);
				
				oStream.flush();
				
				// method.invoke(proxy, method, args);
				InputStream inputStream = socket.getInputStream();
				ObjectInputStream oInputStream = new ObjectInputStream(inputStream);
				Object retObj = oInputStream.readObject();
				
				System.out.println("关闭1？"+socket.isClosed());
				socket.close();
				System.out.println("关闭2？"+socket.isClosed());
				
				return retObj;
			}
			
		});
		
		return (T)newProxyInstance;
	}
}
